package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public String login(User user) {
        // 1.密码加密处理
       String password= user.getPassword();
       password = DigestUtils.md5DigestAsHex(password.getBytes());
       //2.查数据库
       user.setPassword(password);
       User userDB= userMapper.findUserUp(user);
       if (userDB==null){//用户名，密码错误   返回空
           return null;
       }
        //说明:用户名和密码正确 返回秘钥token 要求秘钥唯一
        //uuid 内部hash散列函数,根据当前毫秒数进行散列,几乎可以保证不重复
       String token =UUID.randomUUID().toString();

       return token;
    }


    /**   ||分页查询||
     * select *from User limit 位置
     * **/
    @Override
    public PageResult findUserList(PageResult pageResult) {
        int size = pageResult.getPageSize();
        int startNum = (pageResult.getPageNum() - 1) * size;
        String query = pageResult.getQuery();
        List<User> UserList = userMapper.findUserList(query,size,startNum);
        long total=userMapper.findCount(query);
        pageResult.setTotal(total).setRows(UserList);
       return pageResult;
    }

    // 开关  更新时间
    @Override
    @Transactional
    public void updateStatus(User user) {
        user.setUpdated(new Date());
        userMapper.updataUser(user);

    }


    //添加用户
    @Override
    public void addUser(User user) {
        //更新时间
        Date date = new Date();
        //密码加密
        String password= user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(password).setStatus(true).setCreated(date).setUpdated(date);
        userMapper.addUser(user);
    }

    //数据回显
    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    //修改客户信息  + 时间更新
    @Override
    public void updateUser(User user) {
        user.setUpdated( new Date());
        userMapper.updateUser(user);
    }

    //删除客户信息
    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }

}
